/*
 * @Author: xiaosihan 
 * @Date: 2023-06-30 00:57:01 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2023-12-08 00:54:07
 */

import clsx from "clsx";
import { useEffect, useRef } from "react";
import styles from "./index.module.less";

type ListProps = {
    children: React.ReactNode;
    request: () => void;
    list: any[];
    hasNext: boolean;
    loading: boolean;
    height?: string;
    className?: string;
};

const InfiniteScroll: React.FC<ListProps> = ({
    children,
    request,
    list,
    hasNext,
    loading,
    height = 'calc(100% - 53px)',
    className
}) => {
    const scrollDomRef = useRef<HTMLDivElement>(null);

    // 首次加载判断是否超出第一屏
    const needLoop = async () => {
        const scrollHeight = scrollDomRef.current?.scrollHeight;
        const clientHeight = scrollDomRef.current?.clientHeight;
        if (scrollHeight! <= clientHeight!) {
            await request();
        }
    }


    useEffect(() => {
        if (list.length) {
            (async () => {
                await new Promise((resolve) => setTimeout(resolve, 100));
                if (hasNext) {
                    needLoop();
                }
            })()
        }
    }, [list, hasNext])


    const onScroll = (e: any) => {
        let scrollBottom = e.target.scrollHeight - e.target.offsetHeight - e.target.scrollTop;
        if (scrollBottom < 20 && !loading && hasNext) {
            request();
        }
    }

    return (
        <div
            className={clsx(styles.infiniteScroll, className)}
            style={{ height }}
            ref={scrollDomRef}
            onScroll={onScroll}
        >
            {children}
            {!hasNext && <div className={styles.no_more} >--没有更多了--</div>}
        </div>

    );

}

export default InfiniteScroll;